package com.example.smart.controller;

import cn.hutool.crypto.SecureUtil;
import com.example.common.config.JwtHelper;
import com.example.common.util.R;
import com.example.common.util.Utils;
import com.example.smart.pojo.User;
import com.example.smart.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/user/")
@Tag(name = "显示用户数据")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Resource
    private JwtHelper jwtHelper;

    @PreAuthorize("hasAuthority('user:list')")
    @Operation(summary = "获得所有的用户数据")
    @GetMapping(value = "/getAllUser")
    public R getAllUser() {
        List<User> userList = userService.list();
        return R.ok("查询所有用户数据成功").data("userList", userList);
    }

    @Operation(summary = "登录用户")
    @PostMapping(value = "/login")
    public R login(@RequestBody User users) {
        Map<String, Object> map = userService.login(users);
        if (map.get("state").equals("success")) {
            Map<String, Object> maps = new HashMap<>();
            maps.put("user", users);
            maps.put("token", map.get("token"));
            return R.ok("用户登录成功").data(maps);
        } else {
            return R.ok("用户登录失败").data(map);
        }
    }

   /* @Operation(summary = "查询用户点赞和收藏数据")
    @GetMapping(value = "/getUserLikeStar")
    public R getUserLikeStar(@RequestParam("userId") String userId,
                             @RequestParam("likeId") String likeId,
                             @RequestParam("starId") String starId) {
        // 调用服务层方法，根据参数查询用户点赞和收藏数据
        UserLikeStar userLikeStar = userService.getUserLikeStar(userId, likeId, starId);
        return R.ok("按照用户编号查询数据成功").data("userLikeStar", userLikeStar);
    }*/

    @Operation(summary = "注册用户")
    @PostMapping(value = "/register")
    public R addUser(@RequestBody User user) {
//        Digester md5 = new Digester(DigestAlgorithm.MD5);
//        user.setPassword(md5.digestHex(user.getPassword() + Utils.salt()));
        String salt = Utils.salt();
        user.setPassword(SecureUtil.md5(user.getPassword() + salt));
        user.setUserSalt(salt);
        boolean flag = userService.save(user);
        if (flag) {
            String jwtToken = jwtHelper.getToken(user.getUserId(), user.getUserName(), "user");
            return R.ok("注册用户成功").data("token", jwtToken);
        } else {
            return R.error("注册用户失败");
        }
    }

    @PreAuthorize("hasAuthority('user:delete')")
    @Operation(summary = "注销用户数据")
    @DeleteMapping(value = "/deleteUser/{id}")
    public R deleteUser(@PathVariable("id") Integer userId) {
        boolean flag = userService.removeById(userId);
        if (flag) {
            return R.ok("注销用户成功");
        } else {
            return R.error("注销用户失败");
        }
    }

    @PreAuthorize("hasAuthority('user:getById')")
    @Operation(summary = "按照用户编号查询数据")
    @GetMapping(value = "/getUserById/{id}")
    public R getByIdUser(@PathVariable("id") Integer userId) {
        User user = userService.getById(userId);
        return R.ok("按照用户编号查询数据成功").data("user", user);
    }

    @PreAuthorize("hasAuthority('user:update')")
    @Operation(summary = "修改用户数据")
    @PutMapping(value = "/updateUser")
    public R updateUser(@RequestBody User user) {
//        Digester md5 = new Digester(DigestAlgorithm.MD5);
//        user.setPassword(md5.digestHex(user.getPassword() + Utils.salt()));
        String salt = Utils.salt();
        user.setPassword(SecureUtil.md5(user.getPassword() + salt));
        user.setUserSalt(salt);
        boolean flag = userService.updateById(user);
        if (flag) {
            return R.ok("修改用户成功");
        } else {
            return R.error("修改用户失败");
        }
    }
}
